# js103_rule.py
# js101_rule.py
import sys
from pathlib import Path

# 获取 template 目录的绝对路径（根据实际结构调整）
current_file = Path(__file__)
template_dir = current_file.parent.parent  # 上两级目录


sys.path.append(str(template_dir))

# 现在可以正常导入
from utils import date_offset_handler,date_handler,build_key,random_int
from base_rule import BaseRule
from DataProcessor import DataProcessor
import random
import pandas as pd

class JS103_Rule(BaseRule):
    def __init__(self, project_info):
        """
        需要的参数：
        project_info: ['']
        position: 基础底 / 基础顶
        
        """
        sheet_name = "JS103"  # 统一 sheet 名称
        super().__init__(sheet_name, project_info)


        instance_values = project_info.get("instance_values", {})
        design_elevation = float(instance_values.get("设计高程", 0))

        # 添加基础字段
        self.add_field("桩号、部位", lambda p: p['project_info']['施工部位'])

        # 日期字段
        self.add_field("施工日期", date_offset_handler(0), data_type="date", format="%Y年%m月%d日")
        self.add_field("检测、记录日期", date_offset_handler(0), data_type="date", format="%Y年%m月%d日")
        self.add_field("现场监理签字日期", date_offset_handler(0), data_type="date", format="%Y年%m月%d日")
        self.add_field("自检员签字日期", date_offset_handler(0), data_type="date", format="%Y年%m月%d日")
        
        #桩号、部位
        for i in range(1, 6):
            def make_handler_str(i_):
                return lambda _: f"{project_info['施工部位']}{i_}"
            
            self.add_field(f"桩号、部位{i}",
                        make_handler_str(i),
                        data_type="string",
                        target_cells=[f"A{i+5}"])

        design_elevations = [round(design_elevation + random.uniform(-0.005, 0.005), 3)for _ in range(5)]

        # 添加设计高程字段
        for i in range(1, 6):
            self.add_field(
                f"设计高程({i})",
                lambda _: "{:.3f}".format(design_elevations[i - 1]),  # 👈 增加格式化
                target_cells=[f"B{i+5}"],
                data_type="string"
            )

        # 添加高差字段（±5 mm）
        for i in range(1, 6):
            self.add_field(
                f"高差({i})",
                lambda _: str(random_int(-5, 5)(_)),
                target_cells=[f"C{i+5}"],
                data_type="string"
            )

        # 添加实测高程字段 = 对应的设计高程 + 高差 / 1000
        for i in range(1, 6):
            def make_handler(idx):
                def handler(_):
                    # 获取当前项的设计高程
                    design = design_elevations[idx - 1]
                    # 获取对应的高差值
                    key = build_key(self.sheet_name, f"高差({idx})")
                    diff = int(self.rules[key]["handler"](_))
                    return str(round(design + diff / 1000, 3))
                return handler

            self.add_field(
                f"实测高程({i})",
                make_handler(i),
                target_cells=[f"D{i+5}"],
                data_type="string"
            )
    def process(self,**kwargs):
        """
        封装处理逻辑，直接返回结果
        :param data_file_path: 数据文件路径（Excel/CSV）
        :return: 处理后的 DataFrame
        """
        data_file_path=current_file.parent / '模板数据.xlsx'
        df = pd.read_excel(data_file_path)
        rules = self.get_rules()

        processor = DataProcessor(base_data=df, project_info=self.project_info, rules=rules)
        results = processor.process_dataframe(df)

        return results

if __name__ == "__main__":
    PROJECT_BASE_INFO ={
    '施工单位':'浙江交工宏途交通建设有限公司',
    '监理单位':'浙江浙中建设工程管理有限公司',
    '单位工程':'路基工程',
    '分部工程':'涵洞、通道',
    '分项工程':'主体结构',
    '施工日期':'2024/05/31',
    '施工部位':'K59+639圆管涵',
    '设计坐标(X,Y)':(3243273.926,509154.842),
    '长':44.5,#圆管涵长度
    '宽':4,#圆管涵宽度
    '基础宽度':2759,
    '基础厚度':300,
    '基础顶高程':66035,
    '设计高程':66,#基础高程
    '断面尺寸长度':1250,
    '断面尺寸宽度':275.9,
    '断面尺寸高(厚)度':30,
    '基础混凝土强度（砂浆）等级':'C25',
    '基础设计混凝土（砂浆）用量':'15',
    '基础实际混凝土（砂浆）用量':'16',
    '护壁混凝土强度（砂浆）等级':'C25',
    '护壁设计混凝土（砂浆）用量':'15',
    '护壁实际混凝土（砂浆）用量':'16',
} 

    rule = JS103_Rule(PROJECT_BASE_INFO)
    results = rule.process()
    print(results)